<template>
  <a-modal
    :title="`消息${model&&model.id>0?'编辑':'新增'}`"
    :width="840"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" :labelCol="{sm: {span: 4}}" :wrapperCol="{sm: {span: 20}}" :selfUpdate="true">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="model && model.id > 0" label="ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="标题">
          <a-input v-decorator="['title', {rules: [{ required: true, message: '标题不能为空' }]}]" placeholder="请输入标题"/>
        </a-form-item>
        <a-form-item label="消息类型">
          <a-select v-decorator="['type', {rules: [{ required: true, message: '请选择消息类型' }]}]" placeholder="请输入消息类型">
              <a-select-option v-for="it in typeArr" :key="it.id" :value="Number(it.id)">{{it.text}}</a-select-option>
            </a-select>
        </a-form-item>
        <a-form-item label="消息内容">
          <AWM-editor
            :content="content"
            @change="contentChange"
          ></AWM-editor>
          <!-- <a-textarea v-decorator="['content']" :rows="4" placeholder="请输入消息内容"/> -->
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import AWMEditor from './AWMeditor'
// 表单字段
const fields = ['title', 'type', 'content', 'id']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    typeArr: {
      type: Array,
      default: () => []
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  components:{
    AWMEditor
  },
  data () {
    return {
      form: this.$form.createForm(this),
      content:''
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      
      if(this.model){
        this.model && this.form.setFieldsValue(pick(this.model, fields))
      }else{
        console.log(11111)
        
      }
      
    })
    this.$watch('visible', (n) => {
      if(n){
        this.form.setFieldsValue({type: 1})
      }
    })
  },
  methods:{
    contentChange(val){
      this.content = val
    }
  }
}
</script>
